package com.mlink.ai.chat.ui.fragment


import android.app.Dialog
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.util.DisplayMetrics
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import com.mlink.ai.chat.assistant.robot.databinding.FragmentEnsureExitBinding

class EnsureExitDialogFragment : DialogFragment() {

    private val binding: FragmentEnsureExitBinding by lazy {
        FragmentEnsureExitBinding.inflate(layoutInflater)
    }
    var listener: OnDialogClickListener? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        initView()
        return binding.root
    }

    override fun onStart() {
        super.onStart()
        dialog?.run {
            window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
            val localDisplayMetrics = DisplayMetrics()

            (requireActivity()).windowManager.defaultDisplay.getMetrics(localDisplayMetrics)
            val width = localDisplayMetrics.widthPixels

            window?.let {
                val params = it.attributes
                params.width = width / 7 * 6
                it.attributes = params
            }
        }
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return super.onCreateDialog(savedInstanceState).apply {
            setOnKeyListener { _, keyCode, keyEvent ->
                if (keyCode == KeyEvent.KEYCODE_BACK && keyEvent.action == KeyEvent.ACTION_UP) {
                    dismiss()
                    true
                } else {
                    false
                }
            }
        }
    }

    private fun initView() {
        binding.tvEnsure.setOnClickListener { listener?.onEnsure() }
        binding.tvCancel.setOnClickListener { listener?.onCancel() }
    }

    interface OnDialogClickListener {
        fun onEnsure()
        fun onCancel()
    }
}